package com.atguigu.yygh.hosp.receive;

import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.rabbit.RabbitService;
import com.atguigu.yygh.rabbit.utils.MqConst;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class OrderReceiver {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    //rabbitmq监听注解
    @RabbitListener(bindings = @QueueBinding(//queuebinding注解是进行绑定使用
            value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),//队列名称，是否持久化
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),//交换机名称
            key = {MqConst.ROUTING_ORDER}//对应的路由key
    ))
    //监听到消息要消费的方法
    public void receiver(OrderMqVo orderMqVo, Message message, Channel channel) throws IOException {
        if (orderMqVo.getAvailableNumber() != null){
            //下单成功更新预约数
            Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            scheduleService.update(schedule);
        } else {
            Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
            Integer availableNumber = schedule.getAvailableNumber();
            schedule.setAvailableNumber(availableNumber + 1);
            scheduleService.update(schedule);
        }

        //发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if(null != msmVo) {
            //向交换机队列发送消息
            //参数： 1：交换机名称 2：路由key  3：要发送的消息，传入对象，但是工具类会把传入的对象转成json格式进行发送
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
    }
    }
}
